var {
  VueLoaderPlugin
} = require('vue-loader'); // vue-loader解析还需要VueLoaderPlugin
var webpack = require('webpack');
var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin'); // 构建新HTML页面
var glob = require('glob');
var Cleanwebpackplugin = require('clean-webpack-plugin');

function htmls() {
  // 通过 html-webpack-plugin 生成的 HTML 集合
  let HTMLPlugins = [];
  var pages = getEntry('./src/pages/**/*.html');
  for (var pathname in pages) {
    const htmlPlugin = new HtmlWebpackPlugin({
      filename: 'pages/' + pathname + '.html',
      template: pages[pathname],
      chunks: [pathname],
      minify: {
        // 传递 html-minifier 选项给 minify 输出
        // "removeAttributeQuotes": true,
        // "removeComments": true,
        // "removeEmptyAttributes": true,
      }
    });
    HTMLPlugins.push(htmlPlugin);
  }
  return HTMLPlugins;
}

function getEntry(globPath) {
  var entries = {},
    pathname;
  glob.sync(globPath).forEach((filePath) => {
    pathname = filePath.substring(filePath.lastIndexOf('\/') + 1, filePath.lastIndexOf('.'));
    entries[pathname] = filePath;
  });
  return entries;
}

module.exports = {
  entry: getEntry('./src/js/**/*.js'),
  output: {
    path: path.resolve(__dirname, 'dist'),
    publicPath: '/',
    filename: 'js/[name].js?v=1.0.0'
  },
  module: {
    // 模块规则
    rules: [
      /* 用来解析vue后缀的文件 */
      {
        test: /.vue$/,
        use: ['vue-loader']
      },
      /* 用来解析css后缀的文件 */
      {
        test: /.css$/,
        use: ['style-loader', 'css-loader']
      }
    ]
  },
  // 模块解析
  resolve: {
    // 自动解析确定的扩展,使用户在引入模块时不带扩展
    extensions: ['.js', '.vue', '.json'],
    alias: {
      // 创建vue别名，来确保模块引入变得更简单
      'vue': 'vue/dist/vue.js',
      '@': path.resolve(__dirname, 'src')
    }
  },
  // 用来开启一个Web服务
  devServer: {
    contentBase: path.resolve(__dirname, "dist"),
    compress: true, // 一切服务都启用gzip 压缩
    port: 9000,
    host: '10.33.178.212',
    hot: true, // 启用 webpack 的模块热替换特性,模块修改不刷新页面
    // inline: false,
    // 在浏览器全屏页面上显示错误，默认是false
    overlay: {
      warnings: true,
      errors: true
    },
    // progress: true, // 将运行进度输出到控制台
    // open: true, // 打开浏览器页面
    historyApiFallback: { // mode:'history';路由history模式下的配置
      rewrites: [{
        from: /.*/,
        // to: path.posix.resolve('/', 'index.html')
        to: path.resolve('/', 'index.html')
      }]
    }
  },
  plugins: [
    new Cleanwebpackplugin(['dist']),
    new VueLoaderPlugin(),
    // 启用 webpack 的模块热替换特性
    new webpack.HotModuleReplacementPlugin(),
    // 生成新的HTML页面
    new HtmlWebpackPlugin({
      template: 'index.html', // html的模版
      filename: 'index.html',
      chunks: ['index']
    }),
    ...htmls(),
    // new HtmlWebpackPlugin({
    //   template: 'src/pages/home.html', // html的模版
    //   filename: 'pages/home.html',
    //   chunks: ['']
    // })
  ]
}